//
//  LaunchImageViewController.m
//  iOS切图小工具
//
//  Created by Super on 2018/5/15.
//  Copyright © 2018年 Super. All rights reserved.
//

#import "LaunchImageViewController.h"

#import "NSImage+DM.h"
#import "NSImage+Catgory.h"

@interface LaunchImageViewController () <NSTextFieldDelegate,NSControlTextEditingDelegate>

@property (weak) IBOutlet NSTextField *iphoneXImagePathTextField;
@property (weak) IBOutlet NSTextField *iphonePlusImagePathTextField;
@property (weak) IBOutlet NSTextField *oldIphoneImagePathTextField;
@property (weak) IBOutlet NSTextField *resultPathTextField;
@property (weak) IBOutlet NSTextField *iphoneXImagePathErrorTextField;
@property (weak) IBOutlet NSTextField *iphonePlusImagePathErrorTextField;
@property (weak) IBOutlet NSTextField *oldIphoneImagePathErrorTextField;
@property (weak) IBOutlet NSTextField *resultPathErrorTextField;

@end

@implementation LaunchImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
    [self initStatus];
}

- (void)initStatus {
    self.resultPathTextField.stringValue = [self addCutImageFolderPathWithPath:[self getDesktopPath]];
    
}

- (NSString *)getDesktopPath {
    NSString *bundel = [[NSBundle mainBundle] resourcePath];
    NSString *deskTopLocation = [[bundel substringToIndex:[bundel rangeOfString:@"Library"].location] stringByAppendingFormat:@"Desktop"];
    return deskTopLocation;
}

- (NSString *)addCutImageFolderPathWithPath:(NSString *)path {
    NSString *cutImagePath = [NSString stringWithFormat:@"%@", path];
    return cutImagePath;
}

- (IBAction)onTapSelectButton:(id)sender {
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setCanChooseFiles:NO];//是否能选择文件file
    [panel setCanChooseDirectories:YES];//是否能打开文件夹
    [panel setAllowsMultipleSelection:NO];//是否允许多选file

    NSInteger finded = [panel runModal]; //获取panel的响应
    if (finded == NSModalResponseOK) {
        //  NSFileHandlingPanelCancelButton = NSModalResponseCancel;NSFileHandlingPanelOKButton  = NSModalResponseOK,
        for (NSURL *url in [panel URLs]) {
            //这个url是文件的路径
            //同时这里可以处理你要做的事情 do something
            NSLog(@"--->%@",url.path);
            self.resultPathTextField.stringValue = url.path;
        }
    }
}

- (IBAction)onTapCreateImageViewButton:(id)sender {
    if ([self queryPathIsCorrect]) {
        NSDictionary *data = [LaunchImageViewController getDictionaryFromFile:@"launchImageInfoDefs.plist"];
        [self scaleImageWithImgInfo:data];
    }
}

- (void)scaleImageWithImgInfo:(NSDictionary *)parentImgInfo {
    NSString *iphoneXImagePath = self.iphoneXImagePathTextField.stringValue;
    NSString *iphonePlusImagePath = self.iphonePlusImagePathTextField.stringValue;
    NSString *oldIphoneImagePath = self.oldIphoneImagePathTextField.stringValue;
    
    if (iphoneXImagePath.length == 0) {
        iphoneXImagePath = iphonePlusImagePath;
    }
    
    if (oldIphoneImagePath.length == 0) {
        oldIphoneImagePath = iphonePlusImagePath;
    }
    
    NSImage *iphoneXImage = [[NSImage alloc] initWithContentsOfFile:iphoneXImagePath];
    NSImage *iphonePlusImage = [[NSImage alloc] initWithContentsOfFile:iphonePlusImagePath];
    NSImage *oldIphoneImage = [[NSImage alloc] initWithContentsOfFile:oldIphoneImagePath];
    
    NSArray *iphoneXImgInfoList = [parentImgInfo objectForKey:@"1125*2436"];
    NSArray *iphonePlusImgInfoList = [parentImgInfo objectForKey:@"1242*2208"];
    NSArray *oldIphoneImgInfoList = [parentImgInfo objectForKey:@"640*960"];
    
    [self scaleImageWithParentImgInfoList:iphoneXImgInfoList parentImg:iphoneXImage];
    [self scaleImageWithParentImgInfoList:iphonePlusImgInfoList parentImg:iphonePlusImage];
    [self scaleImageWithParentImgInfoList:oldIphoneImgInfoList parentImg:oldIphoneImage];
    [self bundleFileCopyToFolderPath:[self addCutImageFolderPathWithPath:self.resultPathTextField.stringValue] originalFileName:@"launchImageContents.json" fileName:@"Contents.json" existsCover:YES];
}

- (void)scaleImageWithParentImgInfoList:(NSArray *)parentImgInfoList parentImg:(NSImage *)parentImg {
    for (NSDictionary *infoItem in parentImgInfoList) {
        [self scaledImageWithInfo:infoItem parentImg:parentImg];
    }
}

- (void)scaledImageWithInfo:(NSDictionary *)infoItem parentImg:(NSImage *)parentImg {
    NSString *fileName = [infoItem objectForKey:@"fileName"];
    NSString *width = [infoItem objectForKey:@"width"];
    NSString *height = [infoItem objectForKey:@"height"];
    NSImage *scaledImage = [self scaleToSize:parentImg size:CGSizeMake(width.floatValue/2, height.floatValue/2)];
    [self saveScaledImageWithImage:scaledImage fileName:fileName];
}

//压缩图片尺寸
- (NSImage *)scaleToSize:(NSImage *)img size:(CGSize)size {
    NSImage *scaledImage = [img reSize:size];
    return scaledImage;
}

- (void)saveScaledImageWithImage:(NSImage *)image fileName:(NSString *)fileName {
    //创建一个目录
    NSString *filePath = [self.resultPathTextField.stringValue stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@", fileName]];
    
    NSData *imageData = [image TIFFRepresentation];
    [image lockFocus];
    NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
    [image unlockFocus];
    [imageRep setSize:[image size]];
    
    // png
    NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:NSImageGamma];
    NSData * data = [imageRep representationUsingType:NSPNGFileType properties:imageProps];
    [data writeToFile:filePath atomically:YES];
}

- (BOOL)queryPathIsCorrect {
    BOOL result = YES;
    if (![self isImgaeType:self.iphonePlusImagePathTextField.stringValue]) {
        result = NO;
        self.iphonePlusImagePathErrorTextField.hidden = NO;
    } else {
        self.iphonePlusImagePathErrorTextField.hidden = YES;
    }
//    if (![self isImgaeType:self.iphoneXImagePathTextField.stringValue]) {
//        result = NO;
//        self.iphoneXImagePathErrorTextField.hidden = NO;
//    } else {
//        self.iphoneXImagePathErrorTextField.hidden = YES;
//    }
//    if (![self isImgaeType:self.oldIphoneImagePathTextField.stringValue]) {
//        result = NO;
//        self.oldIphoneImagePathErrorTextField.hidden = NO;
//    } else {
//        self.oldIphoneImagePathErrorTextField.hidden = YES;
//    }
    if (self.resultPathTextField.stringValue.length == 0) {
        result = NO;
        self.resultPathErrorTextField.hidden = NO;
    } else {
        self.resultPathErrorTextField.hidden = YES;
    }
    return result;
}

- (BOOL)isImgaeType:(NSString *)str {
    return [str hasSuffix:@".jpg"]||[str hasSuffix:@".JPG"]||[str hasSuffix:@".png"]||[str hasSuffix:@".PNG"];
}

//根据文件名获取字典
+ (NSDictionary*)getDictionaryFromFile:(NSString *)fileName {
    NSString *cfgFilePath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];;
    NSDictionary *data = [NSDictionary dictionaryWithContentsOfFile:cfgFilePath];
    if (nil == data || [data count] <= 0) {
        NSLog(@"Miss read data from->[%@]", cfgFilePath);
        return nil;
    }
    NSLog(@"%@->loadDefs:[%@]",self, data);
    return data;
}

- (void)bundleFileCopyToFolderPath:(NSString *)folderPath originalFileName:(NSString *)originalFileName fileName:(NSString *)fileName existsCover:(BOOL)cover {
    BOOL success;
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *targetPath = [folderPath stringByAppendingPathComponent:fileName];
    if(!cover) {
        success = [fileManager fileExistsAtPath:targetPath];
        if (success) return;
    } else {
        [fileManager removeItemAtPath:targetPath error:&error];
    }
    NSString *bundlePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:originalFileName];
    //如果文件存在了则不能覆盖，所以前面才要先把它删除掉
    success = [fileManager copyItemAtPath:bundlePath toPath:targetPath error:&error];
    if(!success)
        NSLog(@"'%@' 文件从 app 包里拷贝到指定目录，失败:%@", fileName, error);
    else
        NSLog(@"'%@' 文件从 app 包里已经成功拷贝到了指定目录。", fileName);
}

@end
